package com.jxtc.enterprise.hr.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxtc.enterprise.common.entity.Department;
import com.jxtc.enterprise.common.entity.User;
import com.jxtc.enterprise.common.entity.VipUser;
import com.jxtc.enterprise.common.entity.VipUserOrderPayment;
import com.jxtc.enterprise.common.mapper.DepartmentMapper;
import com.jxtc.enterprise.common.mapper.UserMapper;
import com.jxtc.enterprise.common.mapper.VipUserMapper;
import com.jxtc.enterprise.common.mapper.VipUserOrderPaymentMapper;
import com.jxtc.enterprise.common.utils.CurrencyUtil;
import com.jxtc.enterprise.common.utils.DateTimeUtil;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import com.jxtc.enterprise.common.vo.PaginationResponseVO;
import com.jxtc.enterprise.hr.dto.HrVipUserOrderPageQueryDTO;
import com.jxtc.enterprise.hr.vo.req.HrVipUserOrderDetailPageQueryReqVo;
import com.jxtc.enterprise.hr.vo.req.HrVipUserOrderPageQueryReqVo;
import com.jxtc.enterprise.hr.vo.resp.HrVipUserInfoRespVo;
import com.jxtc.enterprise.hr.vo.resp.HrVipUserOrderDetailPageQueryRespVo;
import com.jxtc.enterprise.hr.vo.resp.HrVipUserOrderPageQueryRespVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * HR 端，订单管理页面，客户餐订单相关的接口
 */
@RestController
@RequestMapping("/jxtc/enterprise/hr/vipUserOrderManage")
@RequiredArgsConstructor
@Slf4j
public class HrVipUserOrderManageController {

    private final VipUserOrderPaymentMapper vipUserOrderPaymentMapper;
    private final UserMapper userMapper;
    private final DepartmentMapper departmentMapper;
    private final VipUserMapper vipUserMapper;

    /**
     * 3.4.1 分页查询客户餐订单列表
     */
    @PostMapping("/queryVipUserOrderByPage")
    public Result<PaginationResponseVO<HrVipUserOrderPageQueryRespVo>> queryVipUserOrderByPage(@Valid @RequestBody HrVipUserOrderPageQueryReqVo reqVo) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, hr view, /queryVipUserOrderByPage, reqVo: {}", requestId, JSONObject.toJSONString(reqVo));

        // 如果开始时间为空，则设置为最早日期
        String startDate = reqVo.getStartTime();
        if (!StringUtils.hasText(startDate)) {
            startDate = "2024-01-01";
        }

        // 如果结束时间为空，则设置为当前日期的后一天；如果结束时间不为空，则将 yyyy-MM-dd 格式的时间转换成 LocalDate 类型
        String endDate = reqVo.getEndTime();
        if (!StringUtils.hasText(endDate)) {
            endDate = DateTimeUtil.getTomorrowDate();
        }

        Page<HrVipUserOrderPageQueryDTO> page = new Page<>(reqVo.getPage(), reqVo.getSize());
        Page<HrVipUserOrderPageQueryDTO> pageResult = vipUserOrderPaymentMapper.queryVipUserOrderStatisticForHrByCompanyId(page, reqVo.getCompanyId(), startDate, endDate);

        // 构建返回给前端的数据
        List<HrVipUserOrderPageQueryRespVo> records = pageResult.getRecords().stream()
                .map(this::buildVipUserOrderPageQueryRespVo)
                .collect(Collectors.toList());
        PaginationResponseVO<HrVipUserOrderPageQueryRespVo> vo = new PaginationResponseVO<>(pageResult.getTotal(), pageResult.getCurrent(), records);

        log.info("requestId {}, hr view, /queryVipUserOrderByPage, response: {}", requestId, JSONObject.toJSONString(vo));
        return ResultGenerator.genSuccessResult(vo);
    }

    private HrVipUserOrderPageQueryRespVo buildVipUserOrderPageQueryRespVo(HrVipUserOrderPageQueryDTO dto) {
        HrVipUserOrderPageQueryRespVo vo = new HrVipUserOrderPageQueryRespVo();
        vo.setDate(dto.getDateFlag());
        vo.setOrderCount(dto.getOrderCount());
        // ! 当前存在数据库中的客户餐金额是假数据，仅占位使用
        int totalAmountInFen = dto.getTotalAmount() == null ? 0 : dto.getTotalAmount();
        String totalAmountInYuan = CurrencyUtil.fenToYuan(totalAmountInFen);
        vo.setTotalAmount(totalAmountInYuan);
        return vo;
    }


    /**
     * 3.4.2 查询某公司当日客户餐订单详情列表
     */
    @PostMapping("/queryVipUserOrderDetail")
    public Result<PaginationResponseVO<HrVipUserOrderDetailPageQueryRespVo>> queryVipUserOrderDetail(@Valid @RequestBody HrVipUserOrderDetailPageQueryReqVo reqVo) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, hr view, /queryVipUserOrderDetail, reqVo: {}", requestId, JSONObject.toJSONString(reqVo));

        Page<VipUserOrderPayment> page = new Page<>(reqVo.getPage(), reqVo.getSize());
        LambdaQueryWrapper<VipUserOrderPayment> queryWrapper = new LambdaQueryWrapper<VipUserOrderPayment>()
                .eq(VipUserOrderPayment::getCompanyId, reqVo.getCompanyId())
                .eq(VipUserOrderPayment::getDateFlag, reqVo.getDate())
                .orderByDesc(VipUserOrderPayment::getCreateTime);
        Page<VipUserOrderPayment> pageResult = vipUserOrderPaymentMapper.selectPage(page, queryWrapper);

        if (CollectionUtils.isEmpty(pageResult.getRecords())) {
            // 如果分页查询到的数据列表为空，直接返回空列表即可
            PaginationResponseVO<HrVipUserOrderDetailPageQueryRespVo> vo = new PaginationResponseVO<>(pageResult.getTotal(), pageResult.getCurrent(), Collections.emptyList());
            log.info("requestId {}, hr view, /queryVipUserOrderDetail, response: {}", requestId, JSONObject.toJSONString(vo));
            return ResultGenerator.genSuccessResult(vo);
        }

        List<String> employeeIdList = pageResult.getRecords().stream().map(VipUserOrderPayment::getEmployeeId).collect(Collectors.toList());
        List<User> employeeList = userMapper.selectBatchIds(employeeIdList);
        Map<String, User> employeeMap = employeeList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

        List<String> departmentIdList = employeeList.stream().map(User::getDepartmentId).collect(Collectors.toList());
        List<Department> departmentList = CollectionUtils.isEmpty(departmentIdList) ? Collections.emptyList() : departmentMapper.selectBatchIds(departmentIdList);
        Map<String, Department> departmentMap = departmentList.stream().collect(Collectors.toMap(Department::getId, Function.identity()));

        List<HrVipUserOrderDetailPageQueryRespVo> records = pageResult.getRecords().stream()
                .map(dto -> buildHrVipUserOrderDetailPageQueryRespVo(dto, employeeMap, departmentMap))
                .collect(Collectors.toList());
        PaginationResponseVO<HrVipUserOrderDetailPageQueryRespVo> vo = new PaginationResponseVO<>(pageResult.getTotal(), pageResult.getCurrent(), records);
        log.info("requestId {}, hr view, /queryVipUserOrderDetail, response: {}", requestId, JSONObject.toJSONString(vo));

        return ResultGenerator.genSuccessResult(vo);
    }

    private HrVipUserOrderDetailPageQueryRespVo buildHrVipUserOrderDetailPageQueryRespVo(VipUserOrderPayment vipUserOrderPayment, Map<String, User> employeeMap, Map<String, Department> departmentMap) {
        HrVipUserOrderDetailPageQueryRespVo vo = new HrVipUserOrderDetailPageQueryRespVo();
        vo.setVipUserOrderId(vipUserOrderPayment.getId());
        vo.setVipUserId(vipUserOrderPayment.getUserId());
        vo.setVipUserName(vipUserOrderPayment.getUsername());
        vo.setVipUserPhone(vipUserOrderPayment.getPhone());
        vo.setServiceEmployeeId(vipUserOrderPayment.getEmployeeId());
        vo.setOrderName(vipUserOrderPayment.getMealSetName());

        String priceInYuan = CurrencyUtil.fenToYuan(vipUserOrderPayment.getMealSetPrice());
        vo.setPrice(priceInYuan);

        String orderTime = LocalDateTimeUtil.format(vipUserOrderPayment.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN);
        vo.setOrderTime(orderTime);

        User employee = employeeMap.get(vipUserOrderPayment.getEmployeeId());
        if (employee != null) {
            vo.setServiceEmployeeName(employee.getUsername());
            Department department = departmentMap.get(employee.getDepartmentId());
            if (department != null) {
                vo.setServiceEmployeeDepartmentName(department.getName());
            } else {
                // 如果员工表中记录的部门 ID 找不到对应的部门信息，说明此时数据库中数据有问题，记录一下日志方便排查
                log.error("buildVipUserOrderDetailPageQueryRespVo, 该员工的部门信息不存在, employeeId: {}, departmentId: {}", employee.getId(), employee.getDepartmentId());
                vo.setServiceEmployeeDepartmentName("未知部门");
            }
        } else {
            // 找不到员工 ID 对应的员工数据时，返回默认数据方便尽早暴露数据不一致问题
            vo.setServiceEmployeeName("未知员工");
            vo.setServiceEmployeeDepartmentName("未知部门");
        }
        return vo;
    }


    /**
     * 3.4.3 根据客户 ID 查询客户详细信息
     *
     * @param vipUserId 客户 ID
     */
    @GetMapping("/queryVipUserInfoById")
    public Result<HrVipUserInfoRespVo> queryVipUserInfoById(@RequestParam("vipUserId") String vipUserId) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, hr view, /queryVipUserInfoById, request: {}", requestId, vipUserId);

        VipUser vipUser = vipUserMapper.selectById(vipUserId);
        if (vipUser == null) {
            log.warn("requestId {}, hr view, /queryVipUserInfoById, vipUser not found, vipUserId: {}", requestId, vipUserId);
            return ResultGenerator.genFailResult("ID 为 " + vipUserId + " 的客户信息不存在");
        }

        HrVipUserInfoRespVo vo = buildHrVipUserInfoRespVo(vipUser);
        log.info("requestId {}, hr view, /queryVipUserInfoById, response: {}", requestId, JSONObject.toJSONString(vo));

        return ResultGenerator.genSuccessResult(vo);
    }

    private HrVipUserInfoRespVo buildHrVipUserInfoRespVo(VipUser dto) {
        HrVipUserInfoRespVo vo = new HrVipUserInfoRespVo();
        vo.setVipUserId(dto.getId());
        vo.setVipUserName(dto.getUsername());
        vo.setVipUserPhone(dto.getPhone());
        vo.setVipUserCarNo(dto.getCarNo());
        vo.setVipUserCarType(dto.getCarType());
        vo.setVipUserVisitorType(dto.getVisitorType());

        // 生成二维码时填写的用餐份数 - 剩余可点餐份数 = 客户实际用餐份数
        int actualFoodCount = dto.getFoodCount() - dto.getLeftCreateOrderCount();
        vo.setActualFoodCount(String.valueOf(actualFoodCount));

        // 如果客户签到图片链接不为空字符串，则按逗号分割返回图片链接列表
        List<String> vipUserImgUrlList = Collections.emptyList();
        if (StringUtils.hasText(dto.getVipUserImgUrls())) {
            vipUserImgUrlList = Arrays.stream(dto.getVipUserImgUrls().split(",")).collect(Collectors.toList());
        }
        vo.setVipUserImgUrlList(vipUserImgUrlList);

        return vo;
    }
}
